<template>
    <div class="body-content">
        <div class="phot-system-content">
            <div class="phot-system-content-toolbar">
                <div class="toolbar-content">
                    <pui-toolbar @click.right="showContextMenu($event)" :toolbarList="hooksData.sysToolbarList"></pui-toolbar>
                </div>
            </div>
            <div class="phot-system-content-main">
                <div class="left">
                    <ResourceContent ref="ResourceContentRef" @onSearch="searchComponent" :root="mainRef.directoryPath" @openExampleGraph="openExampleGraph" />
                    <!-- <ResourceContent @click.right="showContextMenu($event)" :libraryList="store.state.libraryList" @onSearch="searchComponent" :root="mainRef.directoryPath" @openExampleGraph="openExampleGraph" /> -->
                </div>
                <div class="center">
                    <pui-tabs ref="tabsRef" :tabList="mainRef.workspaceList" @onRemove="removeTab" @onAdd="addTab"
                        @onClickHandle="tabClickHandle" add remove></pui-tabs>
                    <div class="preview-content">
                        <WorkSpace/>
						<div class="content-null" v-show="mainRef.workspaceList.length === 0">
							<div class="img">
								<img draggable="false" src="@/assets/logo_4.png" />
							</div>
							<div class="btn-list">
								<pui-button type="primary" @click="addTab">新建工程</pui-button>
								<pui-button @click="openFolderBrowser">打开工程</pui-button>
							</div>
						</div>
                    </div>
                    <MessageLog @click.right="showContextMenu($event)" ref="MessageLogRef" />
                </div>
                <div class="right">
                    <!-- <ComponentContent @click.right="showContextMenu($event)" /> --><input type="file" class="form-control btn-block" placeholder="" readonly id="input_dir" style="filter:alpha(opacity=0);opacity:0;width: 0;height: 0;" webkitdirectory="" directory="">
                    <ComponentContent ref="ComponentContentRef" />
                </div>
            </div>
        </div>
        <!-- <NewFileDialog mask ref="NewFileDialogRef" @openFolderBrowser="openFolderBrowser" :directoryPath="mainRef.directoryPath" @onClose="mainRef.directoryPath = ''" />
        <NewProjectDialog mask ref="NewProjectDialogRef" @openFolderBrowser="openFolderBrowser" :directoryPath="mainRef.directoryPath" @onClose="mainRef.directoryPath = ''" /> -->
        <NewGraphDialog mask ref="NewGraphDialogRef" @openFolderBrowser="openFolderBrowser" :directoryPath="mainRef.directoryPath" @onClose="mainRef.directoryPath = './photlab'" @sendGraphData="getGraphData" @sendProjectData="getProjectData" />
        <FolderBrowserDialog ref="FolderBrowserDialogRef" @onSubmit="onFolderSubmit" :root="mainRef.directoryPath" />
        <ImportProjectDialog ref="ImportProjectDialogRef" />
        <DeleteProjectDialog ref="DeleteProjectDialogRef" />
        <CloseProjectDialog ref="CloseProjectDialogRef" @closeProject="closeGraph()" />
        <EnvironmentVariablesDialog ref="EnvironmentVariablesRef" />
        <ParameterEditorDialog ref="ParameterEditorRef" />
		<TaskManagementDialog ref="TaskManagementDialogRef"/>
        <SettingDialog ref="SettingRef" />
        <!-- <pui-dialog :maskClick="false" title="新增项目" v-model="mainRef.showAddTabDialog" animate="fade" width="450px">
            <template #content>
                <div>
                    
                </div>
            </template>
        </pui-dialog> -->
    </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { uid_rt } from '@/common/types/base_types'
export default defineComponent({
    name: 'OptiSystemContent'
})
</script>
<script lang="ts" setup>
import mainData from './index'
import useHooks from '@/hooks'
import WorkSpace from './work_space/WorkSpace.vue'
import ResourceContent from '../explorers/resource/ResourceContent.vue'
import ComponentContent from '../explorers/component/ComponentContent.vue'
import MessageLog from '../explorers/message/MessageLog.vue'
import NewFileDialog from '../fileControl/newFile.vue'
import NewProjectDialog from '../fileControl/newProject.vue'
import NewGraphDialog from './NewGraph.vue'
import FolderBrowserDialog from '../fileControl/folderBrowser.vue'
import ImportProjectDialog from '../fileControl/importProject.vue'
import DeleteProjectDialog from '../fileControl/deleteProject.vue'
import CloseProjectDialog from '../fileControl/closeProject.vue'
import EnvironmentVariablesDialog from './EnvironmentVariables.vue'
import TaskManagementDialog from '@/components/common/TaskManagement.vue'
import SettingDialog from './Setting.vue'
import ParameterEditorDialog from './ParameterEditor.vue'
import {libraryService as library ,projectService as project, graphService as graph} from '@/services/phot_client/client'
import { reactive, ref, toRaw, getCurrentInstance, nextTick, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import ContextMenu from '../MenuContext'
import { graphManager } from '@/services/phot_client/graph'
import { engineManager } from '@/services/phot_client/engine'
import { PhotTaskStatus, PhotParameter } from "@/common/types/phot_types"
import core from "./work_space/designer";
import upath from 'upath'

const store = useStore()
const { proxy } = getCurrentInstance() as any
const {
    hooksData
} = useHooks()
const {ipcRenderer} = require('electron')
const mainRef = reactive(mainData.mainRef)
const tabClickHandle = async (e: any) => {
    console.log(e)
    if (e.id === graphManager.photGraph.graphId) return
    mainRef.nowGraphId = e.id
    // await graphManager.saveGraph()
    await graphManager.switchGraph(e.uid)
    await engineManager.switchTask(e.id)
    proxy.$refs.ComponentContentRef.init()
    initProjectTree({name: e.name, path:e.path})
    store.dispatch('setPhotGraph', graphManager.photGraph)
}
const removeTab = async (e: any) => {
    console.group('workspaceList')
    console.log(e.item)
    const graph = toRaw(e.item)
    try {
        proxy.$loading.open('正在保存关闭...')
        await graphManager.saveGraph(graph.id)
        await graphManager.closeGraph(graph.uid, graph.id)
        if (engineManager.taskStatus) {
            await engineManager.cancelTask(graph.id)
        } else {
            engineManager.deleteTask(graph.id)
        }
        let index = 0
        if (mainRef.workspaceList.length < 1) {
            proxy.$refs.ComponentContentRef.clear()
            store.dispatch('setPhotGraph', {})
            initProjectTree({})
            return proxy.$loading.close()
        }
        if (graph.index === mainRef.workspaceList.length - 1) {
            index = mainRef.workspaceList.length - 1
        } else if (graph.index < mainRef.workspaceList.length - 1) {
            index = graph.index
        }
        // console.log(mainRef.workspaceList[index])
        mainRef.nowGraphId = mainRef.workspaceList[index].id
        await graphManager.switchGraph(mainRef.workspaceList[index].uid)
        await engineManager.switchTask(mainRef.nowGraphId)
        proxy.$refs.ComponentContentRef.init()
        initProjectTree({name: mainRef.workspaceList[index].name, path: mainRef.workspaceList[index].path})
        store.dispatch('setPhotGraph', graphManager.photGraph)
        proxy.$loading.close()
    } catch (error) {
        proxy.$toast({
            value: error,
            type: 'error'
        })
        proxy.$loading.close()
    }
    console.groupEnd()
}
const addTab = (e:any, str: string | null) => {
    console.log(e)

    if (!str) {
        proxy.$refs.NewGraphDialogRef.init()
    }
}
const messageListFilter = () => {
    const list = mainRef.selectedLog === '1' ? mainRef.messageLogList.filter(item => item.type === 'warn') :
        mainRef.selectedLog === '2' ? mainRef.messageLogList.filter(item => item.type === 'error') :
            mainRef.selectedLog === '3' ? mainRef.messageLogList.filter(item => item.type === 'success') : mainRef.messageLogList
    return list
}
const searchComponent = async (key: string) => {
    await library.searchComponent(key).then((res: any) => {
        console.log(res)
    }).catch((err: any) => {
        console.log(err)
    })
}
const openFolderBrowser = async (e?: any) => {
    mainRef.directoryPath = './photlab'
    await nextTick()
    proxy.$refs.FolderBrowserDialogRef.init(e)
}
const onFolderSubmit = async (e: any) => {
    // console.log(e)
    proxy.$loading.open()
    try {
        mainRef.directoryPath = upath.normalizeSafe(e.path)
        // GRAPH
        if (e.file.type === 3) {
            // console.log(mainRef.directoryPath)
            await graphManager.openGraph(mainRef.directoryPath)
            const graph = graphManager.photGraph
            console.log('graph:',graph)
            const graphName = graph?.name
            const graphId: any = graph?.graphId
            const uid = graphManager.graphId
            console.log('graphName:',graphName)
            console.log('graphId:',graphId)
            console.log('uid:', uid)
            mainRef.workspaceList.push({
                svgSrc: require(`@/assets/file-icon.svg`),
                name: graphManager.photGraph.name,
                id: graphId,
                uid: graphManager.graphId,
                index: mainRef.workspaceList.length,
                path: mainRef.directoryPath,
                graph
            })
            console.log(mainRef.workspaceList)
            mainRef.nowGraphId = graphId
            await engineManager.createTaskId(graphId)
            addTab(false, 'false')
            await nextTick()
            proxy.$refs.tabsRef.updateCurrentIndex()
            proxy.$refs.ComponentContentRef.init()
            initProjectTree({name: graphName, path: mainRef.directoryPath})
            store.dispatch('setPhotGraph', graph)
            mainRef.directoryPath = './photlab'
            // proxy.$refs.WorkSpaceRef[mainRef.workspaceList.length - 1].initWorkspace()
        }
        proxy.$loading.close()
    } catch (error: any) {
        console.log('err:',error)
        proxy.$toast({
            value: error.code === 800 ? '仿真工程已在队列' : '系统错误，请稍后重试',
            type: 'error'
        })
        mainRef.directoryPath = './photlab'
        proxy.$loading.close()
    }
}
const initProjectTree = (e: any) => {
    console.log(e)
    proxy.$refs.ResourceContentRef.init(e)
}
const getGraphData = async (e: any) => {
    try {
        proxy.$loading.open()
        mainRef.workspaceList.push({
            svgSrc: require(`@/assets/file-icon.svg`),
            name: e.name || '画布',
            id: e.graphId,
            uid: e.uid,
            index: mainRef.workspaceList.length,
            path: e.path,
            graph: e
        })
        mainRef.nowGraphId = e.graphId
        await engineManager.createTaskId(e.graphId)
        await nextTick()
        proxy.$refs.tabsRef.updateCurrentIndex()
        mainRef.directoryPath = './photlab'
        proxy.$refs.ComponentContentRef.init()
        initProjectTree(e)
        store.dispatch('setPhotGraph', graphManager.photGraph)
        proxy.$loading.close()
    } catch (error)  {
        console.log(error)
        proxy.$toast({
            value: '系统错误，请稍后重试',
            type: 'error'
        })
        proxy.$loading.close()
    }
}
// const addGraphParameter = async () => {
//     const list = [
//         { name: 'num_symbols', value: '65536', nameTag: '符号数目' },
//         { name: 'bits_per_symbol', value: '4', nameTag: '每符号比特数' },
//         { name: 'total_baud', value: '60000000000', nameTag: '信号波特率，符号率' },
//         { name: 'up_sampling_factor', value: '2', nameTag: '上采样倍数' },
//         // { name: 'sampling_rate', value: '65536', nameTag: '信号采样率' },
//         { name: 'Reference_frequency', value: '193100000000000', nameTag: '参考频率' },
//     ]
//     for (let i = 0; i < list.length; i++) {
//         const parameter = new PhotParameter()
//         parameter.name = list[i].name
//         parameter.value = list[i].value
//         parameter.nameTag = list[i].nameTag
//         await graphManager.addGraphParameter(parameter)
//     }
// }
const getProjectData = async (e: any) => {
    proxy.$loading.open()
    try {
        mainRef.directoryPath = upath.normalizeSafe(e.path)
        // GRAPH
        await graphManager.openGraph(mainRef.directoryPath)
        const graph = graphManager.photGraph
        console.log('graph:',graph)
        const graphName = graph?.name
        const graphId: any = graph?.graphId
        const uid = graphManager.graphId
        console.log('graphName:',graphName)
        console.log('graphId:',graphId)
        console.log('uid:', uid)
        mainRef.workspaceList.push({
            svgSrc: require(`@/assets/file-icon.svg`),
            name: graphManager.photGraph.name,
            id: graphId,
            uid: graphManager.graphId,
            index: mainRef.workspaceList.length,
            path: mainRef.directoryPath,
            graph
        })
        console.log(mainRef.workspaceList)
        mainRef.nowGraphId = graphId
        await engineManager.createTaskId(graphId)
        addTab(false, 'false')
        await nextTick()
        proxy.$refs.tabsRef.updateCurrentIndex()
        proxy.$refs.ComponentContentRef.init()
        initProjectTree({name: graphName, path: mainRef.directoryPath})
        store.dispatch('setPhotGraph', graph)
        proxy.$loading.close()
    } catch (error: any) {
        console.log('err:',error)
        proxy.$toast({
            value: error.code === 800 ? '仿真工程已在队列' : '系统错误，请稍后重试',
            type: 'error'
        })
        proxy.$loading.close()
    }
}
const closeGraph = async () => {
    try {
        await graphManager.saveGraph()
    } catch (err) {
        proxy.$toast({
            value: err,
            type: 'error'
        })
    }
    await graphManager.closeGraph(graphManager.photGraph.uid, graphManager.photGraph.graphId)
}
const showContextMenu = (e: any) => {
    const menuList = [
        // {
        //     label: '添加文本框',
        //     type: 'add',
        //     fn: () => {}
        // },
        {
            label: '编辑',
            type: 'edit',
            fn: () => {
                proxy.$refs.ParameterEditorRef.init(e.node)
            }
        },
        {
            label: '删除',
            type: 'delete',
            fn: () => {}
        },
    ]
    e.el.preventDefault()
    ContextMenu(e.el, menuList)
}
const getOpenedGraphList = async () => {
    try {
        const openedGraphList = await graphManager.getOpenedGraphList()
        for (let graphId in openedGraphList) {
            if (graphId) {
                try {   
                    await graph.saveGraph(graphId)
                    await graph.closeGraph(graphId)
                } catch (err: any) {
                    proxy.$toast({
                        value: err,
                        type: 'error'
                    })
                }
            }
        }
    } catch (err: any) {
        console.log(err)
    }
}
const openExampleGraph = async (e: any) => {
    proxy.$loading.open()
    try {
        await graphManager.openGraph(upath.normalizeSafe(e.path))
        // await graphManager.openGraph(store.state.ExamplesPath + e.path)
        const graphName = graphManager.graphName
        const uid: any = graphManager.graphId
        const graphId: any = graphManager.photGraph.graphId
        const graph = graphManager.photGraph
        mainRef.workspaceList.push({
            svgSrc: require(`@/assets/file-icon.svg`),
            name: graphName,
            id: graphId,
            uid: uid,
            index: mainRef.workspaceList.length,
            path: upath.normalizeSafe(e.path),
            graph
        })
        mainRef.nowGraphId = graphId
        await engineManager.createTaskId(graphId)
        console.log(engineManager.taskId)
        addTab(false, 'false')
        await nextTick()
        proxy.$refs.tabsRef.updateCurrentIndex()
        proxy.$refs.ComponentContentRef.init()
        initProjectTree({name: graphName, path: upath.normalizeSafe(e.path)})
        store.dispatch('setPhotGraph', graph)
        // proxy.$refs.WorkSpaceRef[mainRef.workspaceList.length - 1].initWorkspace()
        proxy.$loading.close()
    } catch (err) {
        console.log(err)
        proxy.$toast({
            value: '系统错误，请稍后重试',
            type: 'error'
        })
        proxy.$loading.close()
    }
}
onMounted(async () => {
    // await getOpenedGraphList()
    ipcRenderer.on('CommandOrControl+O', () => {
        openFolderBrowser()
    })
    ipcRenderer.on('CommandOrControl+N', () => {
        proxy.$refs.NewGraphDialogRef.init()
    })
    setTimeout(async () => {
        const resourcePath = await ipcRenderer.invoke('resourcePath')
        console.log(resourcePath)
        store.dispatch('setExamplesPath', resourcePath + '\\examples')
        store.dispatch('setFiguresPath', resourcePath + '\\figures')
    }, 500)
})
</script>